local vector2d = require("Vector2D")

M = {}

local maxVelocityPlanet = 180  
local gravity_constant = 7000

local function gravity(player,planet,inPlanet)
    local vp = vector2d:new(player.x, player.y)
    local vi = vector2d:new(planet.x, planet.y)
    vi:sub(vp)
    local magnitud = vi:magnitude()
    vi:normalize()
    local mag2 = magnitud * magnitud
    local fuerza = gravity_constant * planet.gravity/ mag2
    if(inPlanet)then
        local inPlanetF = 4 *(planet.radio + player.radio)  / magnitud
        print(inPlanetF)
        vi:mult(inPlanetF)
        if(player.planet==nil)then
            local vp = vector2d:new(player:getLinearVelocity())            
            player:setLinearVelocity( vp.x * 0.99, vp.y * 0.99 );
        end        
    else
        vi:mult(fuerza)
    end
    player:applyForce(vi.x, vi.y, player.x, player.y)
end


local applyGravity = function(player, planetGroup)
    if (player.planeta == nil) then
        local inPlanets = {}
        local j= 1
        for i = 1, planetGroup.numChildren do
            local vp = vector2d:new(player.x, player.y)
            local vi = vector2d:new(planetGroup[i].x, planetGroup[i].y)
            vi:sub(vp)
            local magnitud = vi:magnitude()
            
            if(magnitud < planetGroup[i].radio + planetGroup[i].atmosfera)then
                --print("in")
                inPlanets[j]= planetGroup[i]
                j = j + 1
            end
            
        end
        if(#inPlanets>0)then
            --print("inplanet")
            for i = 1, #inPlanets do
                gravity(player,inPlanets[i],true)
                
            end
        else    
            for i = 1, planetGroup.numChildren do
                gravity(player,planetGroup[i],false)
                
            end
        end
        --print("vuela")
    else
        gravity(player,player.planeta,true)
        --print("planeta")
    end
    
    
end

M.applyGravity = applyGravity

local jump = function(player)
    local vp = vector2d:new(player.x, player.y)
    local vi = vector2d:new(player.planeta.x, player.planeta.y)
    vp:sub(vi)
    vp:normalize()
    player:applyLinearImpulse(vp.x /1.7, vp.y/1.7, player.x, player.y)
end

M.jump = jump

local speed = function(player)
    --velocidad en planeta
    local vp = vector2d:new(player:getLinearVelocity())
    if (player.planeta ~= nil and vp:magnitude() == 0) then
        player:applyForce( 0.1, 0.1, player.x, player.y )(  );
    elseif (player.planeta ~= nil and vp:magnitude() < maxVelocityPlanet) then
        player:setLinearVelocity( vp.x * 1.1, vp.y * 1.1 );
    elseif (player.planeta ~= nil and vp:magnitude() > maxVelocityPlanet * 2) then
        player:setLinearVelocity( vp.x * 0.9, vp.y * 0.9 );
    end
end

M.speed = speed

return M